import { errorHandle, Useful } from "utils";
import type { UniApiParam } from "@/typings/apiCallBack";
// 同步
function uniAPIWrap(fn: string, ...opt: UniApiParam[] | any[]): any {
    if (typeof fn !== "string" || fn.length < 0) {
        return null;
    }
    // @ts-ignore
    if (typeof uni[fn] === "function") {
        if (!Useful.array(opt)) {
            // @ts-ignore
            return uni[fn]();
        } else {
            // @ts-ignore
            return uni[fn](...opt);
        }
    }
    return null;
}
// 异步
function asyncUniAPIWrap(fn: string, opt?: UniApiParam) {
    if (typeof fn !== "string" || fn.length < 0) {
        return;
    }

    let { success, fail, complete, ...others } = opt || {};
    // @ts-ignore
    if (typeof uni[fn] === "function") {
        // @ts-ignore
        uni[fn]({
            ...others,
            success(res: any) {
                success && success(res);
            },
            fail(err: any) {
                if (fail) {
                    // 转成 自己的error
                    let error = errorHandle.insideErr(err);
                    fail(error);
                }
            },
            complete(res: any) {
                complete && complete();
            },
        });
    }
}

export { uniAPIWrap, asyncUniAPIWrap };
